<script setup>
import {MdEditor} from "md-editor-v3";
import 'md-editor-v3/lib/style.css';
import http from "@/lib/http";
import {Message} from "@arco-design/web-vue";
import {route} from "ziggy-js";

const content = defineModel({
    default: '',
    type: String,
    required: true,
})

const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';

const uploadSingleImage = async (file) => {
    const formData = new FormData();
    formData.append('file', file);
    try {
        const res = await http.post(route('admin.upload.image'), formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
                'X-CSRF-TOKEN': csrfToken
            }
        });
        return res.data.url;  // 假设返回结构为 { data: { url: '...' } }
    } catch (err) {
        console.error(`文件 ${file.name} 上传失败:`, err);
        Message.error(`文件 ${file.name} 上传失败: ${err.message}`);
        return null; // 单个文件失败不影响其他
    }
};


const onUploadImg = async (files,callback) => {
    try {
        const imageUrls = await Promise.all(
            Array.from(files).map(file => uploadSingleImage(file))
        );
        console.log('上传成功:', imageUrls);
        callback(imageUrls.map((url) => url));
    } catch (err) {
        console.error('上传失败:', err);
        Message.error(`文件 ${file.name} 上传失败: ${err.message}`);
    }
}
</script>

<template>
    <MdEditor v-model="content" previewTheme="github"   @onUploadImg="onUploadImg"  />
</template>

<style scoped>

</style>
